package vn.com.vega.chacha.v2.Asynctask;

import vn.com.vega.chacha.v2.ActivityBase;
import vn.com.vega.music.clientserver.JsonPlaylist;
import vn.com.vega.music.objects.Playlist;
import vn.com.vega.music.utils.Const;
import android.content.Intent;

public class CreateNewPlaylist extends BaseAsyncTask {

	public interface CreatePlaylistListener {
		public void startCreatePlaylist();

		public void finishCreatePlaylist();

		public void createPlaylistSuccess();

		public void createPlaylistFail(String message);
	}

	private Playlist playlist;
	private String errorMessage = null;
	private CreatePlaylistListener listener;

	public CreateNewPlaylist(ActivityBase base, Playlist playlist,
			CreatePlaylistListener createListener) {
		super(base);
		// TODO Auto-generated constructor stub
		this.playlist = playlist;
		this.listener = createListener;
	}

	@Override
	protected Void doInBackground(Void... params) {
		// TODO Auto-generated method stub
		try {
			JsonPlaylist jsonPlaylist = JsonPlaylist
					.addNewPlaylist(playlist.title);
			if (jsonPlaylist.isSuccess()) {
				errorMessage = null;
			} else {
				errorMessage = jsonPlaylist.getErrorMessage();
			}
			// DataStore dataStore = DataStore.getInstance();
			// List<Playlist> listPlaylist =
			// dataStore.getUserCreatedPlaylistList();
			// for (Playlist list : listPlaylist) {
			// if (playlist.title.equalsIgnoreCase(list.title)) {
			// errorMessage = "Playlist đã tồn tại!";
			// return null;
			// }
			// }
			// if (dataStore.addPlaylist(playlist)) {
			// errorMessage = null;
			// } else {
			// errorMessage = "";
			// }
		} catch (Exception e) {
			// TODO: handle exception
			errorMessage = null;
		}

		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		// TODO Auto-generated method stub
		if (isCancelled() || !checkIsLive()) {
			return;
		}
		if (errorMessage == null) {
			ActivityBase act = baseActivityRfc.get();
			Intent inten = new Intent();
			// inten.setClass(activityBase, CreateNewPlaylist.class);
			inten.setAction(Const.LIST_PLAYLIST_CHANGE);
			// act.sendStickyBroadcast(inten);
			act.sendBroadcast(inten);
		}

		if (listener != null) {
			if (errorMessage == null) {
				listener.createPlaylistSuccess();
			} else {
				listener.createPlaylistFail(errorMessage);
			}
		}
	}
}
